/**
 * Created by Dell on 2017.10.10.
 */




var Token ='123';
var GYZCJsonLayer = null;
var GYZCJsonLayer_point;
var showOrHide_right = false ;
var showOrHide_left = true ;
var myMap;
var locationLevel = 16;
var stationLayer = new StationInfo();
var turnLevel = 14;
var zoomType;
var Polygons = [],Points = [];
var highLightLayer = null;
var highLightData = {};

$(function(){

    //添加地图-----------------------------begin
        myMap = L.map("maps", {
            crs : L.CRS.EPSG4326,
            center: [29.082, 119.641],
            zoom: 12,
            layers: [normal],
            zoomControl: false,
        });

        $(".zoomIn").on("click",function(){
            myMap.zoomIn();
        });
        $(".zoomOut").on("click",function(){
            myMap.zoomOut();
        });

        drawnItems = L.featureGroup().addTo(myMap);

        var overlayLayers={
            "乡镇界线" : BountTileLayer.tileLayer,
            //"绘制图层":drawnItems,
        };

//      L.control.layers(baseLayers, overlayLayers,{
//          position:"topleft"
//      }).addTo(myMap);

        //测量工具
        var options_measure = {
            localization: 'cn',
            position: 'topleft',
            primaryLengthUnit: 'meters',// 长度单位
            primaryAreaUnit: 'sqmeters',   // 面积单位
            activeColor: '#ff0000',
            completedColor: '#ff0000'
        };
       // var measureControl = L.control.measure(options_measure).addTo(myMap);

        if(myMap.getZoom() <= turnLevel){
            zoomType= false;
        }else{
            zoomType= true;
        }

        //LoadMapdata();
        myMap.on('zoomend', function(e) {
            zoomLayers(e.target.getZoom(),highLightData);
        });

    // 点击获取经纬度
    myMap.on('click', function(e) {
        //var LevelXY = myMap.getZoom()+','+e.latlng.lng+','+e.latlng.lat;
        //test_SearchByXY(LevelXY);
    });


    //添加地图-----------------------------end
    $('.hideBtn_right').css('top',($('.right_panel').height()-$('.hideBtn_right').height()-50)/2+'px');
    $('.hideBtn_left').css('top',($('.left_panel').height()-$('.hideBtn_left').height()-50)/2+'px');
    $(".treelist").height($('.left_panel').height()-$('.treeTabs').height() - 20);
    $('.ctab_cont').css('max-height',($('.right_panel').height()-$('.sortBox').height() - 50)+'px');
    $('.d_cont').css('max-height',($('.right_panel').height()-$('.imagesBox').height()-$('.d_title').height()-$('.baseInfo').height()-$('.d_tabs').height()-85+'px'))

    $('.legBtn').click(function(){
        $(this).hide();
        $('.legInfo').show();
    });

    $('.closeLen').click(function(){
        $('.legInfo').hide();
        $('.legBtn').show();
    });

    // 点击箭头 绘制窗口显示隐藏
    $('.hideBtn_right').click(function(){
        if(showOrHide_right){
            $('.right_panel').animate({right:'-340px'},500);
            $('.drawCon').animate({right:'0px'},500);
            $('.hideIcon_right').addClass('hide');
            showOrHide_right = false;
            $('.leaflet-right .leaflet-control').animate({'margin-right':'20px'},500)
        }else {
            $('.right_panel').animate({right:'0px'},500);
            $('.drawCon').animate({right:'380px'},500);
            $('.hideIcon_right').removeClass('hide');
            showOrHide_right = true;
            $('.leaflet-right .leaflet-control').animate({'margin-right':'380px'},500)
        }
    });

    // 点击箭头 绘制窗口显示隐藏
    $('.hideBtn_left').click(function(){
        if(showOrHide_left){
            $('.left_panel').animate({left:'-340px'},500);
            $('.hideIcon_left').addClass('hide');
            showOrHide_left = false;
            $('.leaflet-left .leaflet-control').animate({'margin-left':'20px'},500);
            $('.myControl,#legendDiv').animate({left:'20px'},500);
            $('.maplayerchange').animate({left:'20px'},500);
        }else {
            $('.left_panel').animate({left:'0px'},500);
            $('.hideIcon_left').removeClass('hide');
            showOrHide_left = true;
            $('.leaflet-left .leaflet-control').animate({'margin-left':'380px'},500);
            $('.myControl,#legendDiv').animate({left:'380px'},500);
            $('.maplayerchange').animate({left:'380px'},500);
        }
    });

    // 树结构tab切换
//  $('.treeTab').click(function(){
//      $(this).addClass('active').siblings().removeClass('active');
//      var index = $(this).index();
//      $('.treelist').eq(index).show().siblings().hide();
//  });

    // 详细信息tab切换
    $('.d_tabs li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
        var index = $(this).index();
        $('.d_tabContent .d_cont').eq(index).show().siblings('.d_cont').hide();
    });

    //点击搜索按钮
    $('#searchBtn').click(function(){
        var searchVal=$.trim($('#searchInput').val());
        var reg =/^\s*$/;  //完全匹配0个或多个空格
        if(! reg.test(searchVal)){
            $('.cardlist').show();
            $('.detailsBox').hide();
            var Region_ID = '';  // 所在地区
            var CHR_ID = '';
            var DWType_ID = '';

            infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,false);
        }else {

        }
    });


    // 返回搜索列表
    $('.d_back').click(function(){
        //highLightLayer.clearLayers();
        $('.detailsBox').hide();
        $('.cardlist').fadeIn();
    });

    // 点击排序
    $('.sortBox').find('li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
    });

    // 排序
    $('#ID').click(function(){
        sortTable($(this),".assetId");
    });
    $('#NAME').click(function(){
        sortTable($(this),".l_title");
    });
    $('#ADDRESS').click(function(){
        sortTable($(this),".addressId");
    });

    ajaxRegion();  //获取区域列表
    //ajaxChr();
   // ajaxDWType();

    $('.ctab_cont').on('click','.c_lists',function(){
        var id = $(this).attr("name");
        $(this).addClass('active').siblings().removeClass('active');
        detailsClick(id);
    });

    $(".slideImg").slide({mainCell:".bd ul",autoPlay:true});

    //console.log($.cookie('userInfo'));
    // 鼠标移到站点名出现提示信息
    $('.showTips').each(function(){
        $(this).mousemove(function(e){
            $('.tdTips p').html($(this).attr('name'));
            $('.tdTips').show().css({
                left:(e.pageX-20)+'px',
                top: (e.pageY-$('.tdTips').height()-10 )+'px'
            });
        });
        $(this).mouseout(function(){
            $('.tdTips').hide();
        });
    });

      $('#statistisDiv').delegate('.closebtn','click',function(){
          $('.statistisDiv').hide();
      });

      $('.imgmap').click(function(){
          myMap.removeLayer(normal);
          myMap.addLayer(Satellite);

      });
      $('.vecmap').click(function(){
          myMap.removeLayer(Satellite);
          myMap.addLayer(normal);
      });

});

function initechart(){
  var myChart = echarts.init(document.getElementById('stachart'));
  // 指定图表的配置项和数据
  var option = {
      tooltip : {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
          orient: 'vertical',
          left: 'left',
          data: ['已达标','未达标']
      },
      series : [
          {
              name: '达标情况',
              type: 'pie',
              radius : '50%',
              center: ['50%', '60%'],
              data:[
                  {value:55, name:'已达标'},
                  {value:45, name:'未达标'},
              ],
              itemStyle: {
                  emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
              }
          }
      ]
  };

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
}

function LoadMapdata(){
	var aaurl = config.serviceUrl+ "/api/Fa";
        $.post(aaurl, {
                "DATA": {
                    "Action": "getGeometry",  //SearchByID,SearchByXY,Search
                    "Token":Token,
                }
            },
            function (data) {
                if(data.GeoJsonPolygons.length>0){
                    for(var i=0;i<data.GeoJsonPolygons.length;i++){
                        if(data.GeoJsonPolygons[i] != null){
                            Polygons.push(data.GeoJsonPolygons[i])
                        }
                    }
                    for(var i=0;i<data.GeoJsonPoints.length;i++){
                        if(data.GeoJsonPoints[i] != null){
                            Points.push(data.GeoJsonPoints[i])
                        }
                    }
                }

                showLayers(myMap.getZoom());
            }
        );
}


//显示到地图
function showLayers(mapZoom,data){
    if(GYZCJsonLayer != null){
        GYZCJsonLayer.clearLayers();
    }
    if(mapZoom <= turnLevel){   //显示点
        GYZCJsonLayer = L.geoJSON(Points, {
            pointToLayer:function(GeoJsonPoints,lng){
                return L.marker(lng,{
                    icon:myIcon.greed
                })
            }
        });
    }else{                               //显示面
        GYZCJsonLayer = L.geoJSON(Polygons, {
            style: function(feature) {
                switch (feature.properties.DWType_Name) {
                    case '行政单位': return {color: "#ff9999"};
                    case '国有企业':   return {color: "#d27406"};
                    case '财政补助事业单位':   return {color: "#04a3e6"};
                    case '参照公务员法管理事业单位':   return {color: "#38c0f8"};
                    case '经费自理事业单位':   return {color: "#75d4fc"};
                    case '其他':   return {color: "#b7e0af"};
                }
            },
        });
    }
    GYZCJsonLayer.bindTooltip(function(layer){
            return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
        })
        .addTo(myMap);

}


function showHighLightLayerJH(mapZoom,data){
    if(highLightLayer != null){
        highLightLayer.clearLayers();
    }
    //显示点
    highLightLayer = L.geoJSON(data.Points, {
        pointToLayer:function(GeoJsonPoints,lng){
            return L.marker(lng,{
                icon:myIcon.red
            })
        }
    });
    setview(data.Points.geometry.coordinates[1],data.Points.geometry.coordinates[0]);
    highLightLayer
    .bindPopup((layer)=>{
    	 var jsonstr = JSON.stringify(layer.feature.properties);
    	 var html = "<div class='tips infowindowncls'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.text +"</h3>"+
                     "<p>地址："+  layer.feature.properties.address +"</p>"+
    	               "<p onclick='showDetailInfo("+ jsonstr +")'>详情</p></div>";
    	 return html;
    })
//  .bindTooltip(function(layer){
//          return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
//      })
    .addTo(myMap);
}

function showHighLightLayer(mapZoom,data){
    if(highLightLayer != null){
        highLightLayer.clearLayers();
    }
    if(mapZoom <= turnLevel){   //显示点
        highLightLayer = L.geoJSON(data.Points, {
            pointToLayer:function(GeoJsonPoints,lng){
                return L.marker(lng,{
                    icon:myIcon.red
                })
            }
        })
    }else{      //显示面
        highLightLayer = L.geoJSON(data.Polygons, {
            style: function(feature) {
                return {color: "#fff600"}
            },
        });
    }
    highLightLayer.bindTooltip(function(layer){
            return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
        })
        .addTo(myMap);
}
//控制地图显示点/面
function zoomLayers(mapZoom,data){

//  if( mapZoom <= turnLevel){
	if( mapZoom <= 21){
        if(zoomType) {
            if(GYZCJsonLayer != null){
                GYZCJsonLayer.clearLayers();
            }
            if(highLightLayer != null){
                highLightLayer.clearLayers();
            }
            GYZCJsonLayer = L.geoJSON(Points, {
                    pointToLayer:function(GeoJsonPoints,lng){
                        return L.marker(lng,{
                            icon:myIcon.greed
                        })
                    }
                })
                .bindTooltip(function(layer){
                    return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
                })
                .addTo(myMap);
            if(data){
                highLightLayer = L.geoJSON(data.Points, {
                    pointToLayer:function(GeoJsonPoints,lng){
                        return L.marker(lng,{
                            icon:myIcon.red
                        })
                    }
                }).addTo(myMap)
            }
            zoomType = false;
        }
    }
    else{
        if(!zoomType){
            if(GYZCJsonLayer != null){
                GYZCJsonLayer.clearLayers();
            }
            if(highLightLayer != null){
                highLightLayer.clearLayers();
            }
            GYZCJsonLayer = L.geoJSON(Polygons, {
                    style: function(feature) {
                        switch (feature.properties.DWType_Name) {
                            case '行政单位': return {color: "#ff9999"};
                            case '国有企业':   return {color: "#d27406"};
                            case '财政补助事业单位':   return {color: "#04a3e6"};
                            case '参照公务员法管理事业单位':   return {color: "#38c0f8"};
                            case '经费自理事业单位':   return {color: "#75d4fc"};
                            case '其他':   return {color: "#b7e0af"};
                        }
                    },
                })
                .bindTooltip(function(layer){
                    return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
                })
                .addTo(myMap);
            if(data){
                highLightLayer = L.geoJSON(data.Polygons, {
                    style: function(feature) {
                        return {color: "#fff600"}
                    },
                }).addTo(myMap);
            }
            zoomType = true;
        }
    }

}

//排序
var sortTable = function($this,selector){
    //console.log($(this));
    if($this.data("isAsc")== null) $this.data("isAsc",true);
    else $this.data("isAsc",!$this.data("isAsc"));

    var $treeList = $(".c_lists");

    $.each($treeList, function(index, node) {
        node.sortValue = $(node).find(selector).text();
    });
    var isAsc = $this.data("isAsc");
    $treeList.sort(function(a,b){
        if(isAsc) {
            if (a.sortValue < b.sortValue) return 1;
            else if(a.sortValue > b.sortValue) return -1;
            else return 0;
        }
        else{
            if (a.sortValue > b.sortValue) return 1;
            else if(a.sortValue < b.sortValue) return -1;
            else return 0;
        }
    });
    $treeList.each(function(index){
        $(this).appendTo($(".ctab_cont"));
        $(this).find(".list_num").text(index+1);
    });
};

var selected;
var nodeData = [];

//区域
function ajaxRegion(){
    $.ajax({
        url:config.serviceUrl+ "/api/Region",
       // url:"http://192.168.0.204:8080/JHCJServcice/resCatalog/getListResCatalog.do",

        type:"Post",
        data:{
            "DATA": {
                "ID": "000",
                "Token" : Token,
            }
        },
        async: true,
        success:function(jsonData){

            var dataRegion = [];
            var regionData = jsonData.Region;

            for(var i=0;i<regionData.length;i++){
                var obj = {};
                obj.id = regionData[i].Region_ID;
                obj.text = regionData[i].Region_Name;
                obj.type = '2';
                obj.children = '';
                dataRegion.push(obj);
            }

            getTree(dataRegion);
        },
    })


}

//单位
function ajaxChr(){
    $.ajax({
        url:config.serviceUrl+ "/api/Chr",
        type:"Post",
        data:{
            "DATA": {
                "Prefix": "071",
                "Token" : Token,
            }
        },
        async: false,
    }).done(function (jsonData) {
        var dataChr = [];
        var CHRData = jsonData.CHR;
        for(var i=0;i<CHRData.length;i++) {
            var obj = {};
            var dataSubChr = [];
            for (var j = 0; j < CHRData[i].subCHR.length; j++) {
                var subObj = {};
                subObj.id = CHRData[i].subCHR[j].CHR_ID;
                subObj.text = CHRData[i].subCHR[j].CHR_Name;
                subObj.type = '2';
                subObj.children = '';
                dataSubChr.push(subObj);
            }
            obj.id = CHRData[i].CHR_ID;
            obj.text = CHRData[i].CHR_Name;
            obj.children = dataSubChr;
            obj.type = '1';
            obj.state = "closed";
            dataChr.push(obj);
        }
        getTree2(dataChr)
    })
}

//单位性质
function ajaxDWType(){
    $.ajax({
        url:config.serviceUrl+ "/api/DWType",
        type:"Post",
        data:{
            "DATA": {
                "ID": "000",
                "Token" : Token,
            }
        },
        async: false,
    }).done(function (jsonData) {
        var dataDWType = [];
        for(var i=0 ;i<jsonData.DWType.length;i++){
            var obj = {};
            obj.id = jsonData.DWType[i].DWType_ID;
            obj.text = jsonData.DWType[i].DWType_Name;
            obj.type = '2';
            obj.children = '';
            dataDWType.push(obj);
        }
        getTree3(dataDWType);
    })
}

// 得到区域树列表
function getTree(dataRegion){
    $("#listTree").tree({
        lines:true,
        animate:true,
        data:testdata,
        onLoadSuccess:function(){
        },
        onClick:function(node){
        },
        onSelect:function(node){

//          var searchVal = '';
//          var DWType_ID = '';
//          var Region_ID = node.id;
//          var CHR_ID = '';
//          if(node.type == '2'){  // 得到树的子列表
//              selected = $('#listTree').tree('getSelected');
//              infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
//          }else if(node.type == '3'){                     // 请求详情
//              detailsClick(node.id);
//          }
//          showOrHide_right = true;

        if(node.level == '3'){
              loadDetailInfo(node);
        }
        if(node.level == '1'){
          $('.right_panel').show().animate({right:'0px'},500);
          $('.hideIcon_right').removeClass('hide');
          showOrHide_right = true;
          $('.cardlist').hide();
          $('.detailsBox').fadeIn();
          $('.d_back,.deleteBtn_2').show();
          $('.clearNewFA,.newFaTitle').hide();
          $('.detailsBox').html('');
          $("#generalinfo").tmpl([node]).appendTo('.detailsBox');
          initechart();
        }
        },
    });

}

// 得到单位树列表
function getTree2(dataChr){
    $("#listTree2").tree({
        lines:true,
        animate:true,
        data: [{
            id:'071',
            text: '主管单位',
            state:'open',
            type:'2',
            children:dataChr,
        }],
        onLoadSuccess:function(){
        },
        onClick:function(node){
        },
        onSelect:function(node){
            var DWType_ID = '';
            var searchVal = '';
            var Region_ID =""  ;
            var CHR_ID = node.id ;
            if(node.type == '2'){  // 得到树的子列表
                selected = $('#listTree2').tree('getSelected');
                infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
            }else if(node.type == '3'){                     // 请求详情
                detailsClick(node.id);
            }
            //$('.right_panel').show().animate({right:'0px'},500);
            //$('.mapBox').animate({right:'340px'},500);
            //$('.hideIcon').removeClass('hide');
            showOrHide_right = true;
        },
    });
}

// 得到单位性质树列表
function getTree3(dataDWType){
    $("#listTree3").tree({
        lines:true,
        animate:true,
        data: [{
            id:'071',
            text: '单位性质',
            state:'open',
            type:'2',
            children:dataDWType,
        }],
        onLoadSuccess:function(){
        },
        onClick:function(){
        },
        onSelect:function(node){
            var Region_ID =""  ;
            var CHR_ID = '' ;
            var DWType_ID = node.id ;
            var searchVal = '';
            if(node.type == '2'){  // 得到树的子列表
                selected = $('#listTree3').tree('getSelected');
                infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
            }else if(node.type == '3'){                     // 请求详情
                detailsClick(node.id);
            }
            //$('.right_panel').show().animate({right:'20px'},500);
            //$('.mapBox').animate({right:'340px'},500);
            //$('.hideIcon').removeClass('hide');
            showOrHide_right = true
        },
    });
}

// 得到树的子节点
/*
* flag: {
*   true:插入树的子内容 + 搜索
*   false：只有搜索
*  }
* */
function infoTreeNode(searchVal,RegionInfoID,CHRInfoID,DWType_ID,flag){
    var url = config.serviceUrl+ "/api/Fa";

    $.post(url, {
            "DATA": {
                "Action": 'Search',
                "Wildcards": searchVal,
                "Region_ID": RegionInfoID,     //可省略
                "CHR_ID": CHRInfoID,      //可省略
                "DWType_ID":DWType_ID, //单位性质
                "Token":Token,
            }
        },
        function (data) {
            if(data.Success == true){
                if(GYZCJsonLayer != null){
                    GYZCJsonLayer.clearLayers();
                }
                $('.right_panel').show().animate({right:'0px'},500);
                $('.hideIcon_right').removeClass('hide');
                showOrHide_right = true;
                $('.cardlist').show();
                $('.detailsBox').hide();
                Polygons = [];
                Points = [];
                var fa = data.FA;
                var result='';
                stationInfo = {};
                nodeData = [];
                if(data.FA != undefined){
                    var lgtdArrays = [];
                    var lttdArrays = [];
                    for(var i=0;i<fa.length;i++){
                        var nodeObj ={};
                        nodeObj.id = fa[i].ID;
                        nodeObj.code = fa[i].CODE;
                        nodeObj.text = fa[i].FA_Name;
                        nodeObj.type = '3',
                            nodeData.push(nodeObj);
                        var obj = fa[i];
                        var y = 28.9,x = 120.03;
                        if(fa[i].GeoJsonPoint){
                            var coordinates = fa[i].GeoJsonPoint.geometry.coordinates;
                            y=coordinates[1];
                            x=coordinates[0];
                            Points.push(fa[i].GeoJsonPoint);
                        }
                        lgtdArrays.push(y);
                        lttdArrays.push(x);
                        if(fa[i].GeoJsonPolygon){
                            Polygons.push(fa[i].GeoJsonPolygon);
                        }

                        result += '<div class="c_lists" name="'+obj.ID+'"> ' +
                            '<div class="clearfix"><b class="list_num fl">'+(i+1)+'</b><h3 class="l_title fl list_tit">'+filValue(obj.FA_Name)+'</h3></div> ' +
                            '<ui> ' +
                            '<li><p>资产编号:&nbsp;</p><b class="assetId">'+filValue(obj.CODE)+'</b></li> ' +
                            '<li><p>房屋用途:&nbsp;</p><b>'+filValue(obj.Purpose)+'</b></li> ' +
                            '<li><p>使用单位:&nbsp;</p><b>'+filValue(obj.SYDW_Name)+'</b></li> ' +
                            '<li><p>坐落位置:&nbsp;</p><b class="addressId">'+filValue(obj.Address)+'</b></li> ' +
                            '</ui> ' +
                            '</div>';

                        stationInfo[obj.ID] = {
                            ID:obj.ID,
                            CODE:obj.CODE,
                            name:obj.FA_Name,
                            Address:obj.Address,
                            Purpose:obj.Purpose,
                            SYDW_Name:obj.SYDW_Name,
                            lgtd:x,
                            lttd:y,
                        };

                    }

                    showLayers(myMap.getZoom());
                    lgtdArrays.sort();
                    lttdArrays.sort();
                    var minLoctions = [lgtdArrays[0],lttdArrays[0]];
                    var maxLoctions = [lgtdArrays[lgtdArrays.length-1],lttdArrays[lgtdArrays.length-1]];
                    MapCenter(minLoctions,maxLoctions);
                }else{
                    result ='<p style="line-height: 30px;text-align: center">当前查询无匹配信息</p>';
                }
                // flag == true: 插入树的子项
                if(flag){
                    if(RegionInfoID != ''){
                        var node = $('#listTree').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree').tree('remove',node[i].target);
                        }
                        $('#listTree').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                    else if(CHRInfoID != ''){
                        var node = $('#listTree2').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree2').tree('remove',node[i].target);
                        }
                        $('#listTree2').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                    else{
                        var node = $('#listTree3').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree3').tree('remove',node[i].target);
                        }
                        $('#listTree3').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                }
                $('.ctab_cont').html(result);
            }
        }
    )
}

var loadDetailInfo = function(node){

    if(highLightLayer != null){
        highLightLayer.clearLayers();
    }

    var coordinates = [28.9, 120.03];
    var stationData = {};
    var geojsonPoint = {
    	geometry:{
    		type:'Point',
    		coordinates:[node.lng,node.lat]
    	},
    	properties:node,
    	type:"Feature"
    };
    stationData.Points = geojsonPoint;
    highLightData.Points = geojsonPoint;
    showHighLightLayerJH(myMap.getZoom(),stationData);
};

function showDetailInfo(property){
    $('.statistisDiv').show();
    var dataArr = [];
    dataArr.push(property);
    $('#statistisDiv').html('');
    $("#statistisinfo").tmpl(dataArr).appendTo('#statistisDiv');

}
// 地块详情
var faInfo = function(data){
    getFaImage(data.FA[0].ID);
    $('.right_panel').show().animate({right:'0px'},500);
    $('.hideIcon_right').removeClass('hide');
    showOrHide_right = true;
    $('.cardlist').hide();
    $('.detailsBox').fadeIn();
    $('.d_back,.deleteBtn_2').show();
    $('.clearNewFA,.newFaTitle').hide();

    var fa = data.FA;
    oldObjInfo = fa[0];
    var result = '';        // 基本信息
    var result_house = '';  //房产概括
    var result_land = '';   //土地概括
    var view3dUrl = '';
    var stationData = {};
    highLightData = {};
    for(var i=0;i<fa.length;i++){
        var coordinates = [28.9, 120.03];
        if(fa[0].GeoJsonPoint){
            coordinates = fa[0].GeoJsonPoint.geometry.coordinates;
            coordinates = [coordinates[1],coordinates[0]];
            stationData.Points = fa[0].GeoJsonPoint;
            highLightData.Points = fa[0].GeoJsonPoint;
        }
        if(fa[0].GeoJsonPolygon){
            stationData.Polygons = fa[0].GeoJsonPolygon;
            highLightData.Polygons = fa[0].GeoJsonPolygon;
        }

        $('.d_title').html('<span id="'+fa[0].ID+'" style="cursor: pointer" onclick="setview('+coordinates+')">'+fa[0].FA_Name+'</span>');
        $('.b_address').html(filValue(fa[0].Address));
        $('.b_area').html('总建筑面积'+filValue(fa[0].AreaOfFloor) +'m²');
        if(filValue(fa[0].AreaOfFloor) ==''){
            $('.b_area').hide();
        }
        result +='<div class="clearfix">' +
            '<p><span>资产名称</span><b id="FA_Name">'+filValue(fa[0].FA_Name)+'</b></p>' +
            '<p><span>所在乡镇</span><b id="Region_Name">'+filValue(fa[0].Region_Name)+'</b></p> ' +
            '<p><span>类别代码</span><b id="FAType_ID">'+filValue(fa[0].FAType_ID)+'</b></p>' +
            '<p><span>资产类别</span><b id="FAType_Name">'+filValue(fa[0].FAType_Name)+'</b></p> ' +
            '<p><span>使用单位性质</span><b id="DWType_Name">'+filValue(fa[0].DWType_Name)+'</b></p> ' +
            '<p><span>主管单位ID</span><b id="ZGDW_ID">'+filValue(fa[0].ZGDW_ID)+'</b></p> ' +
            '<p><span>主管单位</span><b id="ZGDW_Name">'+filValue(fa[0].ZGDW_Name)+'</b></p> ' +
            '<p><span>使用状态</span><b id="UsingStatus">'+filValue(fa[0].UsingStatus)+'</b></p> ' +
            '<p><span>目前用途</span><b id="Purpose">'+filValue(fa[0].Purpose)+'</b></p> ' +
            '<p><span>入账年份</span><b id="AccountDate">'+filValue(fa[0].AccountDate)+'</b></p> ' +
            '<p><span>账面价值</span><b id="BookValue">'+filValue(fa[0].BookValue)+'</b></p> ' +
            '<p><span>市场估值</span><b id="MarketValue">'+filValue(fa[0].MarketValue)+'</b></p> ' +
            '<p><span>已使用月份</span><b id="UsedMonth">'+filValue(fa[0].UsedMonth)+'</b></p> ' +
            '<p><span>预计使用月份</span><b id="UseLife">'+filValue(fa[0].UseLife)+'</b></p> ' +
            '<p><span>备注</span><b id="Remaks">'+filValue(fa[0].Remaks)+'</b></p> ' +
            '</div> ';

        result_house +='<div class="clearfix">' +
            '<p><span>权证所有人</span><b id="CertificateOwner">'+filValue(fa[0].CertificateOwner)+'</b></p>' +
            '<p><span>权证情况</span><b id="PropertyStatus">'+filValue(fa[0].PropertyStatus)+'</b></p>' +
            '<p><span>权证发证日期</span><b id="CertificateDate">'+filValue(fa[0].CertificateDate)+'</b></p> ' +
            '<p><span>房产权证编号</span><b id="CertificateID">'+filValue(fa[0].CertificateID)+'</b></p> ' +
            '<p><span>产权形式</span><b id="PropertyForm">'+filValue(fa[0].PropertyForm)+'</b></p> ' +
            '<p><span>权证类型</span><b id="CertificateType">'+filValue(fa[0].CertificateType)+'</b></p> ' +
            '<p><span>权证用途</span><b id="CertificatePurpose">'+filValue(fa[0].CertificatePurpose)+'</b></p> ' +
            '<p><span>取得方式</span><b id="PropertyAcquire">'+filValue(fa[0].PropertyAcquire)+'</b></p> ' +
            '<p><span>取得日期</span><b id="PurchaseDate">'+filValue(fa[0].PurchaseDate)+'</b></p> ' +
            '<p><span>建筑结构</span><b id="BuildingStructure">'+filValue(fa[0].BuildingStructure)+'</b></p> ' +
            '<p><span>是否允许转让</span><b id="BuildingTransfer">'+filValue(fa[0].BuildingTransfer)+'</b></p> ' +
            '<p><span>总面积</span><b id="AreaOfStructure">'+filValue(fa[0].AreaOfStructure)+'</b></p> ' +
            '<p><span>自用面积</span><b id="AreaOfSelfuse">'+filValue(fa[0].AreaOfSelfuse)+'</b></p> ' +
            '<p><span>闲置面积</span><b id="AreaOfIdle1">'+filValue(fa[0].AreaOfIdle1)+'</b></p> ' +
            '<p><span>公益面积</span><b id="AreaOfPublic1">'+filValue(fa[0].AreaOfPublic1)+'</b></p> ' +
            '<p><span>其他面积</span><b id="AreaOfOthers1">'+filValue(fa[0].AreaOfOthers1)+'</b></p> ' +
            '<p><span>抵押面积</span><b id="AreaOfMortgage1">'+filValue(fa[0].AreaOfMortgage1)+'</b></p> ' +
            '<p><span>出租总面积</span><b id="AreaOfRental1">'+filValue(fa[0].AreaOfRental1)+'</b></p> ' +
            '<p><span>出借总面积</span><b id="AreaOfLend1">'+filValue(fa[0].AreaOfLend1)+'</b></p> ' +
            '<p><span>对外投资面积</span><b id="AreaOfInvest1">'+filValue(fa[0].AreaOfInvest1)+'</b></p> ' +
            '</div> ';

        result_land +='<div class="clearfix">' +
            '<p><span>权证使用人</span><b id="LandUser">'+filValue(fa[0].LandUser)+'</b></p>' +
            '<p><span>权证状况</span><b id="LandPropertyStatus">'+filValue(fa[0].LandPropertyStatus)+'</b></p>' +
            '<p><span>土地权证ID</span><b id="LandCertificateID">'+filValue(fa[0].LandCertificateID)+'</b></p> ' +
            '<p><span>权证所有人</span><b id="LandCertificateOwner">'+filValue(fa[0].LandCertificateOwner)+'</b></p> ' +
            '<p><span>权证用途</span><b id="LandCertificatePurpose">'+filValue(fa[0].LandCertificatePurpose)+'</b></p> ' +
            '<p><span>取得方式</span><b id="LandPropertyAcquire">'+filValue(fa[0].LandPropertyAcquire)+'</b></p> ' +
            '<p><span>权证类型</span><b id="LandCertificateType">'+filValue(fa[0].LandCertificateType)+'</b></p> ' +
            '<p><span>发证时间</span><b id="LandCertificateDate">'+filValue(fa[0].LandCertificateDate)+'</b></p> ' +
            '<p><span>有效日期</span><b id="LandValidDate">'+filValue(fa[0].LandValidDate)+'</b></p> ' +
            '<p><span>图号</span><b id="LandMapID">'+filValue(fa[0].LandMapID)+'</b></p> ' +
            '<p><span>宗地号</span><b id="LandZdID">'+filValue(fa[0].LandZdID)+'</b></p> ' +
            '<p><span>用地性质</span><b id="LandTypeID">'+filValue(fa[0].LandTypeID)+'</b></p> ' +
            '<p><span>土地等级</span><b id="LandClass">'+filValue(fa[0].LandClass)+'</b></p> ' +
            '<p><span>使用权面积</span><b id="AreaOfLand">'+filValue(fa[0].AreaOfLand)+'</b></p> ' +
            '<p><span>共用分摊面积</span><b id="AreaOfLandShare">'+filValue(fa[0].AreaOfLandShare)+'</b></p> ' +
            '<p><span>闲置面积</span><b id="AreaOfIdle2">'+filValue(fa[0].AreaOfIdle2)+'</b></p> ' +
            '<p><span>公益面积</span><b id="AreaOfPublic2">'+filValue(fa[0].AreaOfPublic2)+'</b></p> ' +
            '<p><span>其他面积</span><b id="AreaOfOthers2">'+filValue(fa[0].AreaOfOthers2)+'</b></p> ' +
            '<p><span>抵押面积</span><b id="AreaOfMortgage2">'+filValue(fa[0].AreaOfMortgage2)+'</b></p> ' +
            '<p><span>出租总面积</span><b id="AreaOfRental2">'+filValue(fa[0].AreaOfRental2)+'</b></p> ' +
            '<p><span>出借总面积</span><b id="AreaOfLend2">'+filValue(fa[0].AreaOfLend2)+'</b></p> ' +
            '<p><span>对外投资面积</span><b id="AreaOfInvest2">'+filValue(fa[0].AreaOfInvest2)+'</b></p> ' +
            '</div> ';

        view3dUrl = fa[0].View3d;
        if(view3dUrl == null || view3dUrl == undefined){view3dUrl = 'http://map.baidu.com/';}
    }
    showHighLightLayer(myMap.getZoom(),stationData);
    $('.d_base').html(result);
    $('.d_facility').html(result_house);
    $('.d_land').html(result_land);

    $('.d_title').find('span').trigger('click');

    var str = '<div class="ifr"> ' +
        '<div id="close3D">×</div> ' +
        '<iframe width="1200" height="700" frameborder="0" id="bdIframe" src="'+ view3dUrl +'"></iframe>' +
        '</div>';
    $('#view3D').empty().html(str);
    //查看3D视图
    $('.btn_3D').click(function(){
        $('#view3D').show();
    });
    $('#view3D').on('click','#close3D',function(){
        $('#view3D').hide();
    });

    $(".slideImg").slide({mainCell:".bd ul",autoPlay:true});

}

function getFaImage(id){
    var url = config.baseUrl + "/fa/getFaImage.do";
    $.ajax({
        url: url,
        data:{
            id:id
        },
        type: "post",
        success: function (jsondata) {
            $('.Slide.One').find('img').attr('src',jsondata[0]);
            var fa = jsondata.data;
            var strnum = '';
            var strimg = '';
            if(fa.length > 0){
                for(var i=0;i<fa.length;i++){
                    strnum +='<li>'+(i+1)+'</li>';
                    strimg += '<li><a href="javascript:;" class="Slide One" ><span class="deleteImg" iid="'+ fa[i].iid +'" faid="'+ fa[i].id+'"></span><img src="'+ fa[i].baseString+'" /></a></li> '
                }
                var str = '<div class="hd"><ul>'+ strnum+'</ul> </div> ' +
                    '<div class="bd"> <ul> ' +strimg +'</ul> </div>';
                $('#slideImg').empty().html(str);
                $(".slideImg").slide({mainCell:".bd ul",autoPlay:true});
            }else{
                var str = '<a href="javascript:;" class="Slide One" ><img src="../images/no-1.png" /></a>'
                $('#slideImg').html(str)
            }

        }
    })
}



// 点击详情请求数据
var detailsClick = function(id){
    if(highLightLayer != null){
        highLightLayer.clearLayers();
    }
    var url = config.serviceUrl+ "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "SearchByID",  //SearchByID,SearchByXY,Search
                "ID": id, //配合SearchByID 使用
                "Token":Token,
            }
        },
        function (data) {
            if(data.Success == true){

                faInfo(data)
            }
            else {

            }
        });
};

// 地图定位
var setview = function(lttd,lgtd){
    myMap.setView([lttd,lgtd],locationLevel);
    //var newIcon =RainClassIcon.redIcon;
    //console.log(newIcon)
    //L.marker([lttd, lgtd], {
    //    icon:newIcon,
    //    draggable: false        // 使图标可拖拽
    //}).add(newPointLayer);
    //console.log(123123)
}

var filValue = function(x){
    if(x==="" || typeof(x) == "undefined" || x==null || x == "undefined"){
        return "";
    }else {
        return x;
    }
};

// 根据经纬度获取地块
var test_SearchByXY = function(LevelXY) {
    var url = config.serviceUrl + "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "SearchByXY",     //SearchByID,SearchByXY,Search
                "LevelXY": LevelXY,  //配合SearchByXY 使用
                "Token": Token
            }
        },
        function (data) {
            if(data.Success == true){
                if(data.FA && data.FA.length>0){
                    faInfo(data);
                }
            }
        });
};
